<template>
  <scroll-view class="visibleList" scroll-y="true" @scroll="onScroll" :scroll-top="scrollTop">
    <template v-if="pageInfo.status === 'nodata'">
      <my-empty class="empty" :text="EmptyText" />
    </template>
    <template v-else>
      <view class="List" :style="{ height: ListHeight + 'px' }">
        <template v-for="(item, index) in List" :key="index">
          <template
            v-if="
              height * index >= old.scrollTop - delay &&
              height * index <= old.scrollTop + scrollHeight + delay
            "
          >
            <view class="item" :style="{ height: height + 'px', top: height * index + 'px' }">
              <slot name="custom" :item="item" :index="index"></slot>
            </view>
          </template>
        </template>
      </view>
      <view class="loading" v-if="pageInfo.status">
        <my-loadmore @reload="reload" :status="pageInfo.status" />
      </view>
    </template>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref, watch, computed, nextTick, onMounted, onUpdated } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import MyEmpty from '../MyEmpty/MyEmpty.vue'
import MyLoadmore from '../MyLoadmore/MyLoadmore.vue'
import { debounce } from '@/utils/tools'
const props = defineProps({
  pageInfo: {
    default: () => {
      return {
        nodate: false,
        status: '' // '' nodata looading nomore error
      }
    }
  },
  List: {
    default: []
  },
  scrollHeight: {
    default: 0
  },
  scrollTo: {
    default: {
      top: 0,
      change: false
    }
  },
  height: {
    default: 50
  },
  EmptyText: {
    default: '暂无数据'
  },
  delay: {
    default: 150
  }
})

const ListHeight = computed(() => {
  return props.List.length * props.height
})

const emit = defineEmits(['onReload', 'update:scrollTo'])
const reload = () => {
  emit('onReload')
}

const ScrollAction = debounce((val) => {
  scrollTop.value = val.top
}, 150)

watch(
  () => {
    return {
      List: props.List,
      scrollTo: props.scrollTo
    }
  },
  (val) => {
    if (val.scrollTo.change && val.List.length) {
      scrollTop.value = old.value.scrollTop
      nextTick(() => {
        emit('update:scrollTo', {
          top: val.top,
          change: false
        })
        ScrollAction(val.scrollTo)
      })
    }
  },
  {
    deep: true
  }
)

const scrollTop = ref(0)
const old = ref({
  scrollTop: 0
})

const onScroll = (e) => {
  old.value.scrollTop = e.detail.scrollTop
}
</script>

<style scoped lang="scss">
.visibleList {
  height: 100%;
  width: 100%;
}

.List {
  position: relative;

  .item {
    position: absolute;
    width: 100%;
  }
}

.empty {
  display: flex;
  flex: 1 1 auto;
  flex-direction: column;
  width: 100%;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 20rpx 0;
}
</style>
